//
//  AddressListViewController.m
//  HongFuShop
//
//  Created by chirui on 2017/8/15.
//  Copyright © 2017年 Shui. All rights reserved.
//

#import "AddressListViewController.h"
#import "NewAddressViewController.h"

@interface AddressListViewController ()<UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate>{
    
    UITableView * _tableView;
    NSArray * _dataArray;
    UIView * noBodyView;
    NSString * addressIdStr;
    
}

@end

@implementation AddressListViewController

-(void)viewWillAppear:(BOOL)animated {

    [self getAddressListForNet];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    TitleView(@"收货地址")
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"img_nav_bg"] forBarMetrics:UIBarMetricsDefault];
   
//    self.navigationItem.rightBarButtonItem = [UIBarButtonItem rightItemWithIcon:@"icon_address_add" target:self action:@selector(addBtnClick)];
    
     noBodyView = [NothingMessageView creatNothingMessageViewFrame:CGRectMake(WIDTH/2-100, (HEIGHT-64)/2-150, 200, 200) andMessageStr:@"没有相关内容！" onView:nil];
    
    [self creatTableView];
    
    [self creatEndView];
    
      self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"icon_nav_renter" target:self action:@selector(backBtnClick)];
}

-(void)backBtnClick{

    [self.navigationController popViewControllerAnimated:YES];
}


-(void)creatEndView{
    
   
    UIView * endView =[[UIView alloc]init];
    
    if (ISPX) {
        endView.frame = CGRectMake(0, HEIGHT-64-48-34, WIDTH, 48+32);
    }else{
        endView.frame = CGRectMake(0, HEIGHT-64-48, WIDTH, 48);
    }
    endView.backgroundColor = NavBackColor;
    
    UIButton * endBtn =[UIButton buttonWithType:UIButtonTypeSystem];
    endBtn.frame = CGRectMake(0, 0, WIDTH, 48);
    endBtn.backgroundColor = NavBackColor;
    [endBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [endBtn setTitle:@"添加收货地址" forState:UIControlStateNormal];
    [endBtn addTarget:self action:@selector(addBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
    [endView addSubview:endBtn];
    [self.view addSubview:endView];
}


-(void)back{
    
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)addBtnClick{

    NewAddressViewController * new =[[NewAddressViewController alloc]init];
    [self.navigationController pushViewController:new animated:YES];

}

-(void)creatTableView {
    
    _tableView =[[UITableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT -48) style:UITableViewStyleGrouped];
    if (ISPX) {
        
        _tableView.frame = CGRectMake(0, 0, WIDTH, HEIGHT-48-34);
    }
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    UIView * view =[[UIView alloc]init];
    _tableView.tableFooterView = view;
    [self.view addSubview:_tableView];
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 130;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.01;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 0.01;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    return nil;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString * cellId = @"cellId";
    
    UITableViewCell * cell =[tableView dequeueReusableCellWithIdentifier:cellId ];
    if (cell==nil) {
        
        cell =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellId];
    }else {
        while ([cell.contentView.subviews lastObject]!=nil) {
            
              [(UIView *)[cell.contentView.subviews lastObject] removeFromSuperview];
        }
    }

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSDictionary * dic = _dataArray[indexPath.row];
    
    cell.contentView.backgroundColor =[UIColor groupTableViewBackgroundColor];
    UIView * bgView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 120)];
    bgView.backgroundColor = [UIColor whiteColor];

    
    UILabel * nameLabel = [self creatLabelFrame:CGRectMake(10, 10, 120, 20) andTextColor:[UIColor blackColor] andText:dic[@"fullname"] andFont:15 andAliment:NSTextAlignmentLeft onView:bgView];
    
    UILabel *phoneLabel=  [self creatLabelFrame:CGRectMake(140, 10, WIDTH - 150, 20) andTextColor:[UIColor blackColor] andText:dic[@"phone"] andFont:15 andAliment:NSTextAlignmentRight onView:bgView];
    
    UILabel * addressLabel =   [self creatLabelFrame:CGRectMake(10, 40, WIDTH - 40, 20) andTextColor:[UIColor blackColor] andText:[NSString stringWithFormat:@"%@%@%@%@",dic[@"province"],dic[@"city"],dic[@"county"],dic[@"address"]] andFont:15 andAliment:NSTextAlignmentLeft onView:bgView];
    addressLabel.numberOfLines =2;
    [addressLabel sizeToFit];
    
    
    UIView * lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 80, WIDTH, 0.5)];
    lineView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [bgView addSubview:lineView];
    
    UIButton * moreBtn =[UIButton buttonWithType:UIButtonTypeCustom];
    moreBtn.frame = CGRectMake(10, CGRectGetMaxY(lineView.frame)+10, 100, 25);
    [moreBtn setImage:ImageName(@"icon_shoppingcat_choice_pre") forState:UIControlStateNormal];
    [moreBtn setImage:ImageName(@"icon_shoppingcat_choice") forState:UIControlStateSelected];
    [moreBtn setTitle:@"设为默认" forState:UIControlStateNormal];
    [moreBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [moreBtn setTitleColor:NavBackColor forState:UIControlStateSelected];
    moreBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    moreBtn.tag = 100+indexPath.row;
    [moreBtn addTarget:self action:@selector(moreBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:moreBtn];
    
    if ([dic[@"status"] isEqualToString:@"1"]) {
        moreBtn.selected = YES;
    }else {
        moreBtn.selected = NO;
    }
    
    
    UIButton * deledateBtn =[UIButton buttonWithType:UIButtonTypeCustom];
    deledateBtn.frame = CGRectMake(WIDTH - 90, CGRectGetMaxY(lineView.frame)+10, 80, 25);
     deledateBtn.tag = 100+indexPath.row;
    [deledateBtn setTitle:@"删除" forState:UIControlStateNormal];
    [deledateBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    deledateBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [deledateBtn addTarget:self action:@selector(deledateBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:deledateBtn];
    
    [cell.contentView addSubview:bgView];
    
    
    
    return cell;
}

-(void)moreBtnClick:(UIButton *)btn{
    
    NSDictionary * dic = _dataArray[btn.tag - 100];

    btn.selected = !btn.selected;
    
    [self setAddressDefaultForAddId:dic[@"id"]];
}

-(void)deledateBtnClick:(UIButton *)btn{

    NSDictionary * dic = _dataArray[btn.tag - 100];
    
    [self deledateAddressForAddId:dic[@"id"]];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary * dic = _dataArray[indexPath.row];
    addressIdStr  = dic[@"id"];
     if([self.exChangeGoods isEqualToString:@"choose"]){
        
        
        self.block(dic);
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        
        
    }
}

//地址列表
-(void)getAddressListForNet{
    

    
    NSDictionary * dic = @{@"mid":USER_DEFAULTGet(@"mid"),
                           @"token":USER_DEFAULTGet(@"token")
                           };
    
    
    [PostNetWorking postNetWorkingStr:RequestUrlStr(get_addreddList_api) andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;
        
        if (codeSucess) {
          
            if ([responseObject[@"datas"] isKindOfClass:[NSArray class]]) {
                
                _dataArray = responseObject[@"datas"];
            }
            
            if (_dataArray.count>0) {
                
                noBodyView.hidden = YES;
            }else {
                
                noBodyView.hidden = NO;
                [self.view addSubview:noBodyView];
            }
            
        }else {
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        
        [_tableView reloadData];
    } failed:^(NSError *error) {
        
        SHuiMBHidleYes;
        SHuiMBhudTextTimeStr(@"网络错误，请检查网络");
    }];
}

//设置默认
-(void)setAddressDefaultForAddId:(NSString *)addid{
    
    
    NSDictionary * dic = @{@"mid":USER_DEFAULTGet(@"mid"),
                           @"token":USER_DEFAULTGet(@"token"),
                           @"id":addid
                           };
    [PostNetWorking postNetWorkingStr:RequestUrlStr(set_defaultAddress_api) andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;
        if (codeSucess) {
            
            [self getAddressListForNet];
        }else {
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        
        [_tableView reloadData];
    } failed:^(NSError *error) {
        
        SHuiMBHidleYes;
        SHuiMBhudTextTimeStr(@"网络错误，请检查网络");
    }];
    
}


//设置默认
-(void)deledateAddressForAddId:(NSString *)addid{
    
    
    NSDictionary * dic = @{@"mid":USER_DEFAULTGet(@"mid"),
                           @"token":USER_DEFAULTGet(@"token"),
                           @"id":addid
                           };
    [PostNetWorking postNetWorkingStr:RequestUrlStr(deledate_Address_api) andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;
        if (codeSucess) {
            
            [self getAddressListForNet];
        }else {
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        
        [_tableView reloadData];
    } failed:^(NSError *error) {
        
        SHuiMBHidleYes;
        SHuiMBhudTextTimeStr(@"网络错误，请检查网络");
    }];
    
}


-(UILabel *)creatLabelFrame:(CGRect)rec andTextColor:(UIColor*)col andText:(NSString *)text andFont:(CGFloat)flo andAliment:(NSTextAlignment)aliment onView:(UIView *)view {
    
    
    UILabel * statisLabel =[[UILabel alloc]initWithFrame:rec];
    statisLabel.font = [UIFont systemFontOfSize:flo];
    statisLabel.textColor = col;
    statisLabel.textAlignment = aliment;
    statisLabel.text = text;
    [view addSubview:statisLabel];
    
    return statisLabel;
    
}

@end
